package org.wishwork.api.base.logistics;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wishwork.api.Api;
import org.wishwork.api.token.get.ResponseToken;
import org.wishwork.cache.DefaultMemoryCacheOperator;
import org.wishwork.constant.Constants;
import org.wishwork.context.Context;
import org.wishwork.helper.HttpHelper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 物流API
 * @author: WangYX
 * @create: 2022-04-02 17:30
 * @Version: 1.0.0
 **/
public class LogisticsApi extends Api<List<LogisticsResponse>, LogisticsRequest> {

    private static final Logger log = LoggerFactory.getLogger(LogisticsApi.class);

    private Context context;

    public LogisticsApi(Context context) {
        this.context = context;
    }

    /**
     * 调用聚水潭 物流查询
     *
     * @param logisticsRequest
     * @return
     * @throws Exception
     */
    @Override
    protected String query(LogisticsRequest logisticsRequest) throws Exception {

        ResponseToken token = (ResponseToken) DefaultMemoryCacheOperator.instance().get(Constants.TOKEN);

        String url = "/open/logisticscompany/query";
        //请求参数
        Map<String, Object> params = new HashMap<>();
        if (logisticsRequest.getWmsCoId() != null) {
            params.put("wms_co_id", logisticsRequest.getWmsCoId());
        }
        String biz = JSON.toJSONString(params);
        String result = HttpHelper.sendRequest(token.getAccessToken(), biz, url);
        return result;
    }

    /**
     * 请求完成之后的数据处理
     *
     * @param data             json数据
     * @param logisticsRequest 请求对象
     * @return
     * @throws Exception
     */
    @Override
    protected List<LogisticsResponse> process(JSONObject data, LogisticsRequest logisticsRequest) throws Exception {
        JSONArray datas = data.getJSONArray("datas");
        List<LogisticsResponse> logisticsResponses = datas.toJavaList(LogisticsResponse.class);

        //判断是否还有下一个
        Boolean has_next = data.getBoolean("has_next");
        if (has_next) {
            Integer index = logisticsRequest.getPageIndex();
            LogisticsRequest build = logisticsRequest.toBuilder().pageIndex(++index).build();
            List<LogisticsResponse> result = business(build);
            logisticsResponses.addAll(result);
        }
        return logisticsResponses;
    }
}
